<template>
  <a-modal
    v-model:open="visible"
    :title="title"
    width="50%"
    @cancel="cancel"
    :footer="title !== '详情' ? footer : null"
    @ok="handleOk"
  >
    <a-form
      ref="formRef"
      layout="vertical"
      labelAlign="top"
      style="width: 100%"
      :model="formState"
      :rules="rules"
    >
      <a-row style="width: 100%" :gutter="16">
        <a-col
          :span="item.span"
          :key="item.field"
          v-for="item in config"
          style="width: 100%"
        >
          <a-form-item :label="item.label" :name="item.field">
            <a-input
              v-if="item.component === 'Input'"
              v-model:value="formState[item.field]"
              v-bind="item.componentProps"
            />
            <a-select
              v-if="item.component === 'Select'"
              v-model:value="formState[item.field]"
              v-bind="item.componentProps"
            >
            </a-select>
            <a-date-picker
              v-if="item.component === 'DatePicker'"
              v-model:value="formState[item.field]"
              v-bind="item.componentProps"
            />
          </a-form-item>
        </a-col>
      </a-row>
    </a-form>
  </a-modal>
</template>

<script setup>
import { ref, defineExpose, defineProps, nextTick, h } from "vue";
import { config, rules } from "./form.js";
import { createUser, updateUser } from "@/api/index.js";

const props = defineProps({
  loadData: {
    type: Function,
    default: () => {},
  },
});

const formState = ref({});
const visible = ref(false);
const title = ref("新增");
const loading = ref(false);
const formRef = ref(null);

// 控制表单组件禁用状态
const disabled = () => {
  config.value.forEach((item) => {
    item.componentProps = {
      ...item.componentProps,
      disabled: title.value === "详情",
    };
  });
};

// 弹窗显示控制
const handleVisible = (boolean, name, data) => {
  visible.value = boolean;
  title.value = name;
  formState.value = { ...data };
  disabled();
  formRef.value?.resetFields();
};

// 暴露方法给父组件
defineExpose({
  handleVisible,
});

// 确定提交
const handleOk = async () => {
  loading.value = true;

  try {
    if (title.value === "新增") {
      await formRef.value.validateFields();
      await createUser(formState.value);
      message.success("新增成功");
    } else {
      await updateUser(formState.value);
      message.success("修改成功");
    }
    console.log("111", props);
    props.loadData();
    console.log("222");
    visible.value = false;
    formRef.value.resetFields();
  } catch (error) {
    if (title.value === "新增") {
      message.error("表单校验失败，请检查必填项");
    } else {
      message.error("修改失败，请重试");
    }
  } finally {
    loading.value = false;
  }
};

// 取消/关闭弹窗
const cancel = () => {
  loading.value = false;
  visible.value = false;
  formRef.value?.resetFields();
  formState.value = {};
};
</script>
